<?php
function train_manager_schedule_callback($from = NULL) {
	if(!$from = null) {
		if(!isset($_SESSION['filter'])) {
			return false;
		}
		//We pass the filter session to a variable, then unset this session
		$filter = $_SESSION['filter'];
		$_SESSION['filter'] = array();
	} else {
		$filter = array();
		$filter['from'] = $from;
	}
	
  //add stylesheet and create the breadcrumb
	drupal_add_css(drupal_get_path('module', 'train_manager') . '/css/schedule.css');
  $output = _breadcrumb(1);
	
  //Use $filter (from, to) to build database query
  $query = db_select('trains', 'tr');
  $query->join('train_schedules', 'ts', 'ts.trid = tr.trid');
  $query->fields('tr', array('name'))->fields('ts');
  $query->condition('tr.type', 'tn'); //This page is only for Thong Nhat trains
  $query->condition('ts.train_from', $filter['from']);
	if(isset($filter['to'])) {
		$query->condition('ts.train_to', $filter['to']);
	}
	$schedules = $query->execute()->fetchAll();
  
	$destinations = _get_destination_array(0);
	$filter['from'] = $destinations[$filter['from']];
	$filter['to'] = $destinations[$filter['to']];
	//Render schedule form
  if(count($schedules)) {
		//Use a template to render schedules instead of Drupal form because Drupal Form in this case is too complex, not necessary and time wasted
		$output .= theme_render_template(drupal_get_path('module', 'train_manager') . '/tpl/schedule.tpl.php', array('schedules' => $schedules, 'filter' => $filter));
	} else {
		$output .= '<div id="schedule-no-result">No results found.</div>';
	}
	
	//Train ticket types block
	$output .= _ticket_type_html_render();
	
  return $output;
}

function _ticket_type_html_render() {
	return '<div id="ticket-types-wrapper">
			<div id="ticket-type-title">
				Train Ticket Types:
			</div>
			<div id="ticket-types">
				<div class="wrap-ticket-type first">
					<img src="' . drupal_get_path('module', 'train_manager') . '/images/hard_seat.png" alt="Hard seat" title="Hard seat">
					<h3>Hard seat</h3>
				</div>
				<div class="wrap-ticket-type">
					<img src="' . drupal_get_path('module', 'train_manager') . '/images/soft_seat.png" alt="Soft seat" title="Soft seat">
					<h3>Soft seat</h3>
				</div>
				<div class="wrap-ticket-type">
					<img src="' . drupal_get_path('module', 'train_manager') . '/images/hard_berth.png" alt="Hard berth" title="Hard berth">
					<h3>Hard berth</h3>
				</div>
				<div class="wrap-ticket-type last">
					<img src="' . drupal_get_path('module', 'train_manager') . '/images/soft_berth.png" alt="Soft berth" title="Soft berth">
					<h3>Soft berth</h3>
				</div>
			</div>
		</div>';
}